#!/usr/bin/env python 
# -*- coding: utf-8 -*-
# @Time    : 2018/10/23 20:27
# @Author  : Tang Yang
# @Site    : 
# @File    : server.py
import json

from src.detection.predict_caffe import predict_image
from src.image_stitcher.image_stitcher import ImageStitcher
from src.utils.basic_utils import SkuSpecies  # , complement_square
from src.utils.custom_exception import *
from src.utils.context import Context


class ShelfServer:
    def __init__(self, imgs: list, runtime_context: Context):
        """
        ctor
        :param imgs: 需要检测的图片，如果图片数大于1表示需要拼接
        """
        if len(imgs) < 1:
            raise ValueError("Empty imgs")
        try:
            all_detect_results = predict_image(imgs, runtime_context)
            self._status = "identify_success"
        except BaseException:
            self._status = "identify_failure"
            raise DetectionError("Detecting Error")

        if len(all_detect_results) > 1:
            try:
                self._status = "stitching"
                self._detect_result = ImageStitcher(all_detect_results).get_result(runtime_context.working_size)
                self._status = "stitch_success"
            except BaseException:
                self._status = "stitch_failure"
                raise StitchingError("Stitching Error")
        else:
            self._detect_result = all_detect_results[0]
        if len(self._detect_result.positions) > 0:
            # start = time.clock()
            # self._detect_result = complement_square(self._detect_result, runtime_context)
            # end = time.clock()
            # print("Complement Time: ", end - start)
            self._detect_result.sort_positions()

    def get_response(self):
        if self._status != "stitch_success":
            data = dict(task_status=self._status)
            response = dict(success=True, errorcode=0, requestId=0, data=data)
        else:
            # 将label重复的SKU归到一起
            final_labels = []
            final_scores = []
            final_positions = []
            final_row_col_info = []
            for idx, label in enumerate(self._detect_result.labels):
                if label in final_labels:
                    index = final_labels.index(label)
                    final_scores[index].append(self._detect_result.scores[idx])
                    final_positions[index].append(self._detect_result.positions[idx])
                    final_row_col_info[index].append(self._detect_result.row_col_info[idx])
                else:
                    final_labels.append(label)
                    final_scores.append([self._detect_result.scores[idx]])
                    final_positions.append([self._detect_result.positions[idx]])
                    final_row_col_info.append([self._detect_result.row_col_info[idx]])

            result = []
            for idx, label in enumerate(final_labels):
                sku = SkuSpecies(self._detect_result.img.shape, label, label,
                                 final_positions[idx], final_scores[idx], label, final_row_col_info[idx])
                result.append(dict(goods_name=sku.goods_name, goods_desc=sku.goods_desc, ratio=sku.ratio,
                                   num=sku.num, isShow=sku.is_show, list_rows=sku.list_rows, produce=sku.produce,
                                   crops=sku.crops))

            data = dict(task_status="identify_sucess", rows=len(self._detect_result.detected_boxes),
                        rows_length=self._detect_result.img.shape[1],
                        total_area=self._detect_result.img.shape[0] * self._detect_result.img.shape[1],
                        identifySuccessTimes=0, result=result)
            response = dict(success=True, errorcode=0, requestId=0, data=data)
        return json.dumps(response)

    def get_img(self):
        return self._detect_result.img

    def get_img_after_draw(self):
        return self._detect_result.show()

    @property
    def detect_result(self):
        return self._detect_result
